
from django_redis import get_redis_connection
from utils.cookiesecret import CookieSecret
import json


def merge_cart_cookie_to_redis(request, response):
    # 查询 cookie 中数据
    cookie_str = request.COOKIES.get("carts")
    if not cookie_str:
        return response

    # 解密
    cookie_dict = CookieSecret.loads(cookie_str)
    # 查询 redis 数据库 数据
    client = get_redis_connection("carts")
    redis_data = client.hgetall(request.user.id)
    redis_dict = {int(sku_id.decode()): json.loads(cart_dict.decode()) for sku_id, cart_dict in redis_data.items()}

    # 更新字典
    redis_dict.update(cookie_dict)
    # 遍历修改
    for sku_id in redis_dict.keys():
        client.hset(request.user.id, sku_id, json.dumps(redis_dict[sku_id]))

    # 删除 cookie 的值
    response.delete_cookie('carts')
    return response

